package com.tkjt.pms.modules.kpinew.service.impl;
import com.tkjt.pms.calc.common.IndexCalcParallel;
import com.tkjt.pms.common.utils.DoubleUtil;
import com.tkjt.pms.modules.kpinew.mapper.KpiNewMapper;
import com.tkjt.pms.modules.kpinew.model.ViewConfig;
import com.tkjt.pms.modules.kpinew.service.KpiDataGetService;
import com.tkjt.pms.modules.kpinew.service.KpiNewService;
import com.tkjt.pms.modules.kpinew.vo.KpiViewVo;
import com.tkjt.pms.utils.EsExceptionUtils;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.*;

@Transactional
@Service
public class TkPmsKpisServiceImpl implements KpiNewService {
    @Autowired
    private KpiDataGetService kpiDataGetService;

    private ExecutorService executorService = Executors.newFixedThreadPool(20);

    @Override
    public Result kpiView(KpiViewVo kpiViewVo) {
        String indexYearMonth = kpiViewVo.getIndexYearMonth();
        if(StringUtils.isEmpty(indexYearMonth)){
            return Result.error("参数缺失！");
        }
        String dimensionality = kpiViewVo.getDimensionality();
        String indexDepartGroup = kpiViewVo.getIndexDepartGroup();
        if(dimensionality.equals("growAndValue")){
            List<Map<String,Object>> result = getCondition1(indexYearMonth,indexDepartGroup);
            return Result.ok(result);
        }else if(dimensionality.equals("fuseAndBiz")){
            List<Map<String,Object>> result = getCondition2(indexYearMonth,indexDepartGroup);
            return Result.ok(result);
        }
        return null;
    }

    public Map<String, Object> getFirstIndexCodeData(Map<String,Object> data, Map<String,Object> paramData, String indexYearMonth, String departBiz, String indexDepartGroup){
        Map<String,Object> data1 = new HashMap<>();
        Map<String,Object> paramData1 = (Map<String,Object>)paramData.get("data1");
        data1.put("title",paramData1.get("name"));
        data1.put("type","columnar");
        kpiDataGetService.getData11(data1,(ArrayList<String>)paramData1.get("indexValueCodes"),departBiz,indexYearMonth,indexDepartGroup);
        data.put("data1",data1);
        //园区的时候不需要
        if(StringUtils.isEmpty(indexDepartGroup)){
            //1.2各园区预算达成贡献度data2（柱状图）
            Map<String,Object> data2 = new HashMap<>();
            Map<String,Object> paramData2 = (Map<String,Object>)paramData.get("data2");
            data2.put("title",paramData2.get("name"));
            data2.put("type","columnar");
            kpiDataGetService.getdata12(data2,(ArrayList<String>)paramData2.get("indexValueCodes"),departBiz,indexYearMonth,indexDepartGroup);
            data.put("data2",data2);
            //1.3园区收入占比data3（饼状图）
            Map<String,Object> data3 = new HashMap<>();
            Map<String,Object> paramData3 = (Map<String,Object>)paramData.get("data3");
            data3.put("title",paramData3.get("name"));
            data3.put("type","falls");
            kpiDataGetService.getdata13(data3,(ArrayList<String>)paramData3.get("indexValueCodes"),departBiz,indexYearMonth,indexDepartGroup);
            data.put("data3",data3);
            data.put("length",2);
        }
        //子集的时候不需要
        //1.4业态收入占比data4（饼状图）
        if(StringUtils.isEmpty(departBiz)){
            Map<String,Object> data4 = new HashMap<>();
            Map<String,Object> paramData4 = (Map<String,Object>)paramData.get("data4");
            data4.put("title",paramData4.get("name"));
            data4.put("type","falls");
            kpiDataGetService.getdata14(data4,(ArrayList<String>)paramData4.get("indexValueCodes"),indexYearMonth,indexDepartGroup);
            data.put("data4",data4);
            data.put("length",3);
            if(StringUtils.isNotEmpty(indexDepartGroup)){
                data.put("length",1);
            }
        }
        return data;
    }

    public Map<String, Object> getSecondIndexCodeData(Map<String,Object> data,Map<String,Object> paramData,String indexYearMonth,String departBiz,String indexDepartGroup){
        Map<String,Object> data1 = new HashMap<>();
        Map<String,Object> paramData1 = (Map<String,Object>)paramData.get("data1");
        data1.put("title",paramData1.get("name"));
        data1.put("type","columnar");
        kpiDataGetService.getData21(data1,(ArrayList<String>)paramData1.get("indexValueCodes"),departBiz,indexYearMonth,indexDepartGroup);
        data.put("data1",data1);
        //全国的时候不需要
        if(StringUtils.isEmpty(indexDepartGroup)){
            //2.2各园区预算达成贡献度data2（柱状图）
            Map<String,Object> data2 = new HashMap<>();
            Map<String,Object> paramData2 = (Map<String,Object>)paramData.get("data2");
            data2.put("title",paramData2.get("name"));
            data2.put("type","columnar");
            kpiDataGetService.getdata12(data2,(ArrayList<String>)paramData2.get("indexValueCodes"),departBiz,indexYearMonth,indexDepartGroup);
            data.put("data2",data2);
            //2.3园区收入占比data3（柱状图）
            Map<String,Object> data3 = new HashMap<>();
            Map<String,Object> paramData3 = (Map<String,Object>)paramData.get("data3");
            data3.put("title",paramData3.get("name"));
            data3.put("type","columnar");
            kpiDataGetService.getdata23(data3,(ArrayList<String>)paramData3.get("indexValueCodes"),departBiz,indexYearMonth,indexDepartGroup);
            data.put("data3",data3);
            data.put("length",2);
        }
        //子集的时候不需要
        //2.4业态收入占比data4（柱状图）
        if(StringUtils.isEmpty(departBiz)){
            Map<String,Object> data4 = new HashMap<>();
            Map<String,Object> paramData4 = (Map<String,Object>)paramData.get("data4");
            data4.put("title",paramData4.get("name"));
            data4.put("type","columnar");
            kpiDataGetService.getdata24(data4,(ArrayList<String>)paramData4.get("indexValueCodes"),indexYearMonth,indexDepartGroup);
            data.put("data4",data4);
            data.put("length",3);
            if(StringUtils.isNotEmpty(indexDepartGroup)){
                data.put("length",1);
            }
        }
        return data;
    }

    public Map<String, Object> getThirdIndexCodeData(int index,Map<String,Object> data,Map<String,Object> paramData,String indexYearMonth,String departBiz,String indexDepartGroup){
        Map<String,Object> data1 = new HashMap<>();
        Map<String,Object> paramData1 = (Map<String,Object>)paramData.get("data1");
        data1.put("type","columnar");
        //床位使用率
        if(index == 3){
            data1.put("title","医院床位使用率");
            List<String> allIndexValueCodes = (ArrayList<String>)paramData1.get("indexValueCodes");
            List<String> indexValueCodes = new ArrayList<>();
            indexValueCodes.add(allIndexValueCodes.get(2));
            indexValueCodes.add(allIndexValueCodes.get(3));
            kpiDataGetService.getData11(data1,indexValueCodes,departBiz,indexYearMonth,indexDepartGroup);
        }else{
            data1.put("title",paramData1.get("name"));
            List<String> allIndexValueCodes = (ArrayList<String>)paramData1.get("indexValueCodes");
            List<String> indexValueCodes = new ArrayList<>();
            indexValueCodes.add(allIndexValueCodes.get(0));
            indexValueCodes.add(allIndexValueCodes.get(1));
            kpiDataGetService.getData31(data1,indexValueCodes,departBiz,indexYearMonth,indexDepartGroup);
        }

        data.put("data1",data1);
        if(StringUtils.isEmpty(indexDepartGroup)){
            //3.2各园区预算达成贡献度data2（柱状图）
            Map<String,Object> data2 = new HashMap<>();
            Map<String,Object> paramData2 = (Map<String,Object>)paramData.get("data2");
            data2.put("title",paramData2.get("name"));
            data2.put("type","columnar");
            List<String> allIndexValueCodes = (ArrayList<String>)paramData2.get("indexValueCodes");
            List<String> indexValueCodes = new ArrayList<>();
            //床位使用率
            if(index == 3){
                data2.put("title","各园区床位使用率");
                indexValueCodes.add(allIndexValueCodes.get(2));
                indexValueCodes.add(allIndexValueCodes.get(3));
                kpiDataGetService.getData32(data2,indexValueCodes,departBiz,indexYearMonth,indexDepartGroup);
            }else{
                indexValueCodes.add(allIndexValueCodes.get(0));
                indexValueCodes.add(allIndexValueCodes.get(1));
                kpiDataGetService.getdata12(data2,indexValueCodes,departBiz,indexYearMonth,indexDepartGroup);
            }
            data.put("data2",data2);
            //3.3园区销售占比data3（柱状图）
            Map<String,Object> data3 = new HashMap<>();
            Map<String,Object> paramData3 = (Map<String,Object>)paramData.get("data3");
            data3.put("title",paramData3.get("name"));
            data3.put("type","columnar");
            allIndexValueCodes = (ArrayList<String>)paramData3.get("indexValueCodes");
            indexValueCodes = new ArrayList<>();
            if(index == 3){
                data.put("length",1);
            }else{
                indexValueCodes.add(allIndexValueCodes.get(0));
                kpiDataGetService.getdata23(data3,indexValueCodes,departBiz,indexYearMonth,indexDepartGroup);
                data.put("data3",data3);
                data.put("length",2);
            }
        }
        //子集的时候不需要
        //3.4业态销售占比data4（柱状图）
        if(StringUtils.isEmpty(departBiz)){
            Map<String,Object> data4 = new HashMap<>();
            Map<String,Object> paramData4 = (Map<String,Object>)paramData.get("data4");
            data4.put("title",paramData4.get("name"));
            data4.put("type","columnar");
            kpiDataGetService.getdata34(data4,(ArrayList<String>)paramData4.get("indexValueCodes"),indexYearMonth,indexDepartGroup);
            data.put("data4",data4);
            data.put("length",3);
            if(StringUtils.isNotEmpty(indexDepartGroup)){
                data.put("length",1);
            }
        }
        return data;
    }
    /**
     * 园区筛选为全国或园区   维度为增长与价值
     * @param indexYearMonth
     * @return
     */
    public List<Map<String,Object>> getCondition1(String indexYearMonth,String indexDepartGroup){
        List<Map<String,Object>> result = new ArrayList<>();
        List<Map<String,Object>> dataParams = ViewConfig.getDataParams1();
        List<Future<Map<String,Object>>> taskFutureParents = new ArrayList<Future<Map<String,Object>>>();
        for(int i = 0 ; i < dataParams.size() ; i++){
            int finalI = i;
            Callable callable = new Callable<Map<String,Object>>(){
                @Override
                public Map<String, Object> call() throws Exception {
                    Map<String,Object> data = new LinkedHashMap<>();
                    Map<String,Object> dataParam = dataParams.get(finalI);
                    List<Future<Map<String,Object>>> taskFutures = new ArrayList<Future<Map<String,Object>>>();
                    //1.收入
                    if(finalI == 0){
                        //1.1收入情况data1（柱形图）
                        Map<String, Object> finalData = data;
                        Callable callableParent = new Callable<Map<String,Object>>(){
                            @Override
                            public Map<String, Object> call() throws Exception {
                                return getFirstIndexCodeData(finalData, dataParam,indexYearMonth, null,indexDepartGroup);
                            }
                        };
                        Future<Map<String,Object>> parentFuture = executorService.submit(callableParent);
                        taskFutures.add(parentFuture);
                        List<Map<String,Object>> child = (List<Map<String,Object>>)dataParam.get("child");
                        for(int j = 0 ; j < child.size() ; j++){
                            Map<String,Object> childDataParam = child.get(j);
                            Map<String,Object> childData = new LinkedHashMap<>();
                            Callable callableChild = new Callable<Map<String,Object>>(){
                                @Override
                                public Map<String, Object> call() throws Exception {
                                    return getFirstIndexCodeData(childData, childDataParam,indexYearMonth, childDataParam.get("departBiz").toString(),indexDepartGroup);
                                }
                            };
                            Future<Map<String,Object>> childFuture = executorService.submit(callableChild);
                            taskFutures.add(childFuture);
                        }
                    }
                    //2.EBITDA
                    else if(finalI == 1){
                        //2.1EBITDA情况data1（柱形图）
                        Map<String, Object> finalData1 = data;
                        Callable callableParent = new Callable<Map<String,Object>>(){
                            @Override
                            public Map<String, Object> call() throws Exception {
                                return getSecondIndexCodeData(finalData1,dataParam,indexYearMonth,null,indexDepartGroup);
                            }
                        };
                        Future<Map<String,Object>> parentFuture = executorService.submit(callableParent);
                        taskFutures.add(parentFuture);
                        List<Map<String,Object>> child = (List<Map<String,Object>>)dataParam.get("child");
                        for(int j = 0 ; j < child.size() ; j++){
                            Map<String,Object> childDataParam = child.get(j);
                            Map<String, Object> finalDataParam = childDataParam;
                            Map<String,Object> childData = new LinkedHashMap<>();
                            Callable callableChild = new Callable<Map<String,Object>>(){
                                @Override
                                public Map<String, Object> call() throws Exception {
                                    return getSecondIndexCodeData(childData,finalDataParam,indexYearMonth,finalDataParam.get("departBiz").toString(),indexDepartGroup);
                                }
                            };
                            Future<Map<String,Object>> childFuture = executorService.submit(callableChild);
                            taskFutures.add(childFuture);
                        }
                    }
                    //3.销售
                    else if(finalI == 2){
                        //3.1销售情况data1（柱形图）
                        Map<String, Object> finalData2 = data;
                        Callable callableParent = new Callable<Map<String,Object>>(){
                            @Override
                            public Map<String, Object> call() throws Exception {
                                return getThirdIndexCodeData(0,finalData2,dataParam,indexYearMonth,null,indexDepartGroup);
                            }
                        };
                        Future<Map<String,Object>> parentFuture = executorService.submit(callableParent);
                        taskFutures.add(parentFuture);
                        List<Map<String,Object>> child = (List<Map<String,Object>>)dataParam.get("child");
                        for(int j = 0 ; j < child.size() ; j++){
                            Map<String,Object> childDataParam = child.get(j);
                            Map<String, Object> finalDataParam = childDataParam;
                            Map<String,Object> childData = new LinkedHashMap<>();
                            int index = j+1;
                            Callable callableChild = new Callable<Map<String,Object>>(){
                                @Override
                                public Map<String, Object> call() throws Exception {
                                    return getThirdIndexCodeData(index,childData,finalDataParam,indexYearMonth,finalDataParam.get("departBiz").toString(),indexDepartGroup);
                                }
                            };
                            Future<Map<String,Object>> childFuture = executorService.submit(callableChild);
                            taskFutures.add(childFuture);
                        }
                    }
                    List<Map<String,Object>> childResult = new ArrayList<>();
                    // 等待所有线程执行完成
                    for (int index = 0; index < taskFutures.size(); index++) {
                        try {
                            Map<String,Object> ret = (Map<String, Object>) taskFutures.get(index).get(5, TimeUnit.MINUTES);
                            if(index == 0){
                                data = ret;
                            }else{
                                childResult.add(ret);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    data.put("child",childResult);
                    return data;
                }
            };
            Future<Map<String,Object>> future = executorService.submit(callable);
            taskFutureParents.add(future);
        }
        // 等待所有线程执行完成
        for (int index = 0; index < taskFutureParents.size(); index++) {
            try {
                Map<String,Object> ret = (Map<String, Object>) taskFutureParents.get(index).get(5, TimeUnit.MINUTES);
                result.add(ret);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 园区筛选为全国或园区   维度为融合与业态
     * @param indexYearMonth
     * @return
     */
    public List<Map<String,Object>> getCondition2(String indexYearMonth,String indexDepartGroup){
        List<Future<Map<String,Object>>> taskFuture = new ArrayList<Future<Map<String,Object>>>();
        Map<String,Object> dataParam = ViewConfig.getDataParams2();
        //子集
        List<Map<String,Object>> childParams = (List<Map<String,Object>>)dataParam.get("child");
        List<Map<String,Object>> result = new ArrayList<>();
        Callable callableParent = new Callable<List<Map<String,Object>>>(){
            @Override
            public List<Map<String,Object>> call() throws Exception {
                return getCondition2CommonWay(0,dataParam,indexYearMonth,indexDepartGroup);
            }
        };
        Future<Map<String,Object>> parentFuture = executorService.submit(callableParent);
        taskFuture.add(parentFuture);


        for(int i = 0 ; i < childParams.size() ; i++){
            int index = i+1;
            Map<String,Object> childParam = childParams.get(i);
            Callable callableChild = new Callable<List<Map<String,Object>>>(){
                @Override
                public List<Map<String,Object>> call() throws Exception {
                    return getCondition2CommonWay(index,childParam,indexYearMonth,indexDepartGroup);
                }
            };
            Future<Map<String,Object>> childFuture = executorService.submit(callableChild);
            taskFuture.add(childFuture);
        }

        // 等待所有线程执行完成
        for (int index = 0; index < taskFuture.size(); index++) {
            try {
                List<Map<String,Object>> ret = (List<Map<String,Object>>) taskFuture.get(index).get(5, TimeUnit.MINUTES);
                result.addAll(ret);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public List<Map<String,Object>> getCondition2CommonWay(int index,Map<String,Object> dataParam,String indexYearMonth,String indexDepartGroup){
        List<Map<String,Object>> data = new ArrayList<>();
        String departBiz = dataParam.get("departBiz") == null ? null : dataParam.get("departBiz").toString();
        //1.收入
        Map<String,Object> data1 = new HashMap<>();
        Map<String,Object> paramData1 = (Map<String,Object>)dataParam.get("data1");
        data1.put("title",paramData1.get("name"));
        data1.put("type","columnar");
        kpiDataGetService.getData11(data1,(ArrayList<String>)paramData1.get("indexValueCodes"),departBiz,indexYearMonth,indexDepartGroup);
        data.add(data1);
        //2.EBITDA
        Map<String,Object> data2 = new HashMap<>();
        Map<String,Object> paramData2 = (Map<String,Object>)dataParam.get("data2");
        data2.put("title",paramData2.get("name"));
        data2.put("type","columnar");
        kpiDataGetService.getData21(data2,(ArrayList<String>)paramData2.get("indexValueCodes"),departBiz,indexYearMonth,indexDepartGroup);
        data.add(data2);
        //3.销售
        Map<String,Object> data3 = new HashMap<>();
        Map<String,Object> paramData3 = (Map<String,Object>)dataParam.get("data3");

        data3.put("type","columnar");
        List<String> allIndexValueCodes = (ArrayList<String>)paramData3.get("indexValueCodes");
        List<String> indexValueCodes = new ArrayList<>();
        //床位使用率
        if(index == 3){
            data3.put("title","医院床位使用情况");
            indexValueCodes.add(allIndexValueCodes.get(2));
            indexValueCodes.add(allIndexValueCodes.get(3));
            kpiDataGetService.getData11(data3,indexValueCodes,departBiz,indexYearMonth,indexDepartGroup);
        }else{
            data3.put("title",paramData3.get("name"));
            indexValueCodes.add(allIndexValueCodes.get(0));
            indexValueCodes.add(allIndexValueCodes.get(1));
            kpiDataGetService.getData31(data3,indexValueCodes,departBiz,indexYearMonth,indexDepartGroup);
        }
        data.add(data3);
        return data;
    }


}
